<?php

require_once 'include.php';

use sdk\WeiXin;
use sdk\Db;

define('HYURL', 'http://wx.hui-dian.cn');

$swx = new WeiXin($serverAppName, $serverAppId, $serverAppSecret);
$cwx = new WeiXin($customerAppName, $customerAppId, $customerAppSecret);
$db = new Db($host, $username, $passwd, $schema);

################################################################################
// 以下方法在提交公众号服务器配置信息时被调用
//$cwx->valid();
################################################################################
// 检查微信认证签名
if (!$cwx->checkSignature()) {
    throw new Exception('Invalid Credential');
}

// 检查输入数据
if (empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
    throw new Exception('Empty Post');
}

try {
    // 获得输入数据
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

    // libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
    // the best way is to check the validity of xml by yourself
    // 出于安全角度考虑，防止外部注入
    libxml_disable_entity_loader(true);

    // 读取XML请求
    $post_object = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

    $customer_openid = "$post_object->FromUserName";
    $developer_wxid = "$post_object->ToUserName";

    /* 							
      //store user profile to database
      if (!$this->queryUser($mysqli, $openid, $uid)) {
      // get user profile from wechat server
      $profile	= $this->getUserProfile($openid);
      // store user profile to database
      $this->registerUser($mysqli, $profile);
      // get the newly generated uid
      $this->queryUser($mysqli, $openid, $uid);
      // generate user avatar icon image
      $this->generateUserAvatar($profile->headimgurl, $profile->openid);
      }
     */
    // 从微信公众号获取用户信息
    $profile = $cwx->getProfile($customer_openid);
    $nickname = $profile->nickname;

    // 保存用户信息到慧店数据库
    if ($db->getCustomerId($customer_openid) == null) {
        $db->saveCustomer($profile);
    }
    // 在之后的操作中均使用慧店id，而不是微信提供的openid
    $customer_id = $db->getCustomerId($customer_openid);

    $message_type = "$post_object->MsgType";

    switch ($message_type) {
        // 收到事件推送消息
        case 'event':
            $event = "$post_object->Event";
            $event_key = "$post_object->EventKey";

            switch ($event) {
                // 用户关注公众号
                case 'subscribe':

                    $role = substr($event_key, -1);
                    // 当role为9时，event_key的前半部分为service_id
                    if ($role == 9) {
                        $service_id = substr($event_key, 8, -1);
                        $shop_id = $db->getShopIdByServiceId($service_id);
                        $db->joinShop($customer_id, $shop_id);
                        $db->setCustomerCurrentShop($shop_id, $customer_id);

                        $fileid = $db->getMainImgByServiceId($service_id);
                        $image_url = $cwx->generateDownloadUrl(0, $fileid, 'huidian');
                        $image_full_name = $cwx->saveRemoteFile($image_url);
                        $media_id = $cwx->uploadMediaFile($image_full_name);
                        unlink($image_full_name);

                        $cwx->responseImageXML($customer_openid, $developer_wxid, $media_id);
                        // 否则，event_key的前半部分为shop_id
                    } else {
                        $shop_id = substr($event_key, 8, -1);

                        $db->joinShop($customer_id, $shop_id);
                        $db->setCustomerCurrentShop($shop_id, $customer_id);

                        $content_response = $nickname . '，欢迎关注“美美萌”，您已关注“美丽美甲店”<a href="'
                                . HYURL . '/shop.php?shop_id=$scene_id">点此打开商店页面</a>';
                        $cwx->responseTextXML($customer_openid, $developer_wxid, $content_response);
                    }

                    break;

                // 用户取消关注公众号
                case 'unsubscribe':
                    $content_request = '感谢所有一起度过的时光';
                    $cwx->responseTextXML($customer_openid, $developer_wxid, $content_response);
                    break;

                // 用户扫描二维码 
                case 'SCAN':
                    $role = substr($event_key, -1);
                    // 当role为9时，event_key的前半部分为service_id
                    if ($role == 9) {
                        $service_id = substr($event_key, 0, -1);
                        $shop_id = $db->getShopIdByServiceId($service_id);
                        $db->joinShop($customer_id, $shop_id);
                        $db->setCustomerCurrentShop($shop_id, $customer_id);

                        $fileid = $db->getMainImgByServiceId($service_id);
                        $image_url = $cwx->generateDownloadUrl(0, $fileid, 'huidian');
                        $image_full_name = $cwx->saveRemoteFile($image_url);
                        $media_id = $cwx->uploadMediaFile($image_full_name);
                        unlink($image_full_name);

                        $cwx->responseImageXML($customer_openid, $developer_wxid, $media_id);
                        // 否则，event_key的前半部分为shop_id
                    } else {
                        $shop_id = substr($event_key, 0, -1);
                        $db->joinShop($customer_id, $shop_id);
                        $db->setCustomerCurrentShop($shop_id, $customer_id);

                        $content_response = '您已关注“美丽美甲店”<a href="'
                                . HYURL . '/shop.php?shop_id=$scene_id">点此打开商店页面</a>';
                        $cwx->responseTextXML($customer_openid, $developer_wxid, $content_response);
                    }

                    break;

                default :
                    throw new Exception('欢迎关注美美萌！');
            }

            break;


        // 收到客户文本消息
        case 'text':
            $content_request = trim($post_object->Content);

            $content_response = $content_request;
            $cwx->responseTextXML($customer_openid, $developer_wxid, $content_response);
            break;

        // 收到客户图像消息
        case 'image':
            $media_id = "$post_object->MediaId";
            $query_params = array('access_token' => $cwx->getAccessToken(), 'media_id' => $media_id);
            $image_url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?'
                    . http_build_query($query_params);

            $file_name = uniqid() . '.jpg';
            $image_full_name = OCRIMGBASE . $file_name;
            //save the raw image to raw folder
            exec('curl -G "' . $image_url . '" > ' . $image_full_name);


            //#$imgname = $this->uploadImage("$post_object->MediaId");
            //#$this->insertImage($mysqli, $openid, $imgname);

            $content_response = $media_id;
            $cwx->responseTextXML($customer_openid, $developer_wxid, $content_response);
            break;

        // 收到客户语音消息
        case 'voice':
            break;

        // 收到客户视频消息
        case 'video':
            $media_id = "$post_object->MediaId";
            $content_response = $media_id;
            $cwx->responseTextXML($customer_openid, $developer_wxid, $content_response);
            break;

        default:
            throw new Exception('Unknown Message Type');
    }
} catch (Exception $e) {
    $cwx->responseTextXML($customer_openid, $developer_wxid, $e->getMessage());
}

function insertImage(&$mysqli, $openid, $imgname) {
    $sql_string = 'INSERT INTO Post(uid, imgname, time) 
							VALUES((SELECT uid FROM User WHERE openid= ? ), ? , now());';
    $stmt = $mysqli->prepare($sql_string);
    $stmt->bind_param('ss', $openid, $imgname);
    $stmt->execute();
    $stmt->close();
}

function uploadImage($media_id) {
    $query_params = array('access_token' => $this->accessToken, 'media_id' => $media_id);
    $image_url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?' . http_build_query($query_params);

    $file_name = uniqid() . '.jpg';
    $image_path = RAWIMGBASE . $file_name;
    //save the raw image to raw folder
    exec('curl -G "' . $image_url . '" > ' . $image_path);
    $raw_image = imagecreatefromjpeg($image_path);
    $width = imagesx($raw_image);
    $height = imagesy($raw_image);
    $new_width = 290;
    $new_height = $height * $new_width / $width;
    $new_image = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($new_image, $raw_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    //save processed image to images folder
    imagejpeg($new_image, IMGBASE . $file_name);
    imagedestroy($raw_image);
    imagedestroy($new_image);
    return $file_name;
}

function generateUserAvatar($url, $openid) {
    //change to end character to get a small icon
    $url = substr($url, 0, -1) . '64';
    $icon_full_name = ICONIMGBASE . $openid . '.jpg';
    exec('curl -G "' . $url . '" > ' . $icon_full_name);
    $frame_image = imagecreatefrompng(ICONIMGBASE . 'frame.png');
    $icon_image = imagecreatefromjpeg($icon_full_name);
    imagecopy($icon_image, $frame_image, 0, 0, 0, 0, 64, 64);
    imagejpeg($icon_image, $icon_full_name, 100);

    imagedestroy($frame_image);
    imagedestroy($icon_image);
}

function httpPost($url, $data_string) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    curl_exec($curl);
    $return_content = ob_get_contents();
    ob_end_clean();

    $return_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    return array($return_code, $return_content);
}
